package mx.controller;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

/**
 * 
 * @author Gray-bird
 * 
 */

@Controller
@RequestMapping("/Qrcode")
public class QrcodeController {

	/**
	 * 生成二维码
	 * 
	 * @param resp
	 * @param id
	 * @throws IOException
	 */
	@RequestMapping(value = "/encode", method = { RequestMethod.POST,
			RequestMethod.GET })
	public void getqcode(HttpServletResponse resp, String id)
			throws IOException {
		String url = id;
		if (url != null && !"".equals(url)) {
			ServletOutputStream stream = null;
			try {
				int width = 120;// 图片的宽度
				int height = 120;// 高度
				stream = resp.getOutputStream();
				QRCodeWriter writer = new QRCodeWriter();
				BitMatrix matrix = writer.encode(url, BarcodeFormat.QR_CODE,
						height, width);
				MatrixToImageWriter.writeToStream(matrix, "png", stream);
			} catch (WriterException e) {
				e.printStackTrace();
			} finally {
				if (stream != null) {
					stream.flush();
					stream.close();
				}
			}
		}
	}
}
